//
//  XGContactNotificationCenter.m
//  HuanXin
//
//  Created by monkey on 2019/11/13.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Hyphenate/Hyphenate.h>

#import "XGFriendRequestNotificationCenter.h"
#import "XGFriendRequestNotification.h"

@interface XGFriendRequestNotificationCenter () <EMContactManagerDelegate>
{
    NSMutableArray<XGFriendRequestNotification *> *_notificationArr;
    __weak id<XGContactNotificationCenterDelegate> _delegate;
}

@end

@implementation XGFriendRequestNotificationCenter

#pragma mark - 开放方法

+ (instancetype)shared
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

- (void)setDelegate:(id<XGContactNotificationCenterDelegate>)delegate
{
    _delegate = delegate;
}

- (void)removeDelegate:(id<XGContactNotificationCenterDelegate>)delegate
{
    _delegate = nil;
}

- (NSArray<XGFriendRequestNotification *> *)notificationArr
{
    return _notificationArr;
}

// 更新通知信息
- (void)updateNotification
{
    NSMutableIndexSet *indexSetM = [NSMutableIndexSet indexSet];
    [_notificationArr enumerateObjectsUsingBlock:^(XGFriendRequestNotification * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSolve) {
            [indexSetM addIndex:idx];
        }
    }];
    
    [_notificationArr removeObjectsAtIndexes:indexSetM];
    [self writeToCache];
    
    if ([_delegate respondsToSelector:@selector(didReceiveFriendRequestNotification)]) {
        [_delegate didReceiveFriendRequestNotification];
    }
}

#pragma mark - 私有方法

- (instancetype)init
{
    if (self = [super init]) {
        [self loadCache];
        // 注册好友回调
        [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
    }
    
    return self;
}

- (void)dealloc
{
    // 移除好友回调
    [[EMClient sharedClient].contactManager removeDelegate:self];
}

// 从沙盒读取
- (void)loadCache
{
    _notificationArr = [NSMutableArray array];
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"notifications.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        NSArray<XGFriendRequestNotification *> *result = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithArray:@[
            [NSArray class],
            [XGFriendRequestNotification class]
        ]] fromData:data error:nil];
        [_notificationArr addObjectsFromArray:result];
    }
}

// 保存到沙盒
- (void)writeToCache
{
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"notifications.plist"];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_notificationArr requiringSecureCoding:YES error:nil];
    [data writeToFile:filePath atomically:YES];
}

#pragma mark - EMContactManagerDelegate

- (void)friendRequestDidReceiveFromUser:(NSString *)aUsername message:(NSString *)aMessage
{
    XGFriendRequestNotification *notification = [[XGFriendRequestNotification alloc] init];
    notification.solve = NO;
    notification.name = aUsername;
    notification.message = aMessage;
    notification.time = [[NSDate date] stringWithFormat: @"yyyy-MM-dd HH:mm:ss"];
    [_notificationArr addObject:notification];
    [self writeToCache];
    
    if ([_delegate respondsToSelector:@selector(didReceiveFriendRequestNotification)]) {
        [_delegate didReceiveFriendRequestNotification];
    }
}

@end
